//
//  GMExamResultVC.m
//  Teecloud
//
//  Created by 小熊 on 2018/11/16.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "GMExamResultVC.h"
#import "GMResultCell.h"
#import "GMExamModel.h"
#import "GMAnswerCards.h"
#import "GMMyClassVC.h"
#import "GMHomeVC.h"
#import "GMAnalysisVC.h"
#import "GMExercisesVC.h"
#import "GMExamHeadView.h"
#import "GMAnswerItem.h"
#import "GMAnalysisVC.h"

@interface GMExamResultVC ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *titleName;
@property (weak, nonatomic) IBOutlet UILabel *passName;
@property (weak, nonatomic) IBOutlet UILabel *useTime;
@property (weak, nonatomic) IBOutlet UILabel *avScore;
@property (weak, nonatomic) IBOutlet UILabel *topScore;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UIButton *lookBtn;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) GMExamModel *baseModel;
@end

@implementation GMExamResultVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"考试结果";
    //覆盖返回按键
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem backItemWithImage:[UIImage imageNamed:@"left-white-64"] WithHighlightedImage:[UIImage imageNamed:@"left-gray-64"] Target:self action:@selector(backItemClick) title:@"  "];
    [self.collectionView registerNib:[UINib nibWithNibName:@"GMResultCell" bundle:nil] forCellWithReuseIdentifier:@"GMResultCell"];
    [self.collectionView  registerNib:[UINib nibWithNibName:@"GMExamHeadView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"GMExamHeadView"];
    [self getGMResultData];
}
-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}
-(void)getGMResultData{
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"examId":self.examId,
                          };
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetTestResult&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                GMExamModel *model = [GMExamModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                self.baseModel = model;
                [self updataWithModel:model];
                [self.dataArr removeAllObjects];
                [self.dataArr addObjectsFromArray:model.AnswerCards];
                [self.collectionView reloadData];
            }else{
                UIAlertController *alert  = [UIAlertController zj_alertControllerWithTitle:@"提示" message:[responseObject objectForKey:RESULT_NAME_Message] optionStyle:OptionStyleStyleOnlyOK OkTitle:@"好的" cancelTitle:@"" okBlock:^{
                    [self.navigationController popViewControllerAnimated:YES];
                } cancelBlock:^{
                    [self.navigationController popViewControllerAnimated:YES];
                }];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络出错" toView:self.view];
        }
    }];
}
-(void)updataWithModel:(GMExamModel *)model{
    self.titleName.text = [NSString stringWithFormat:@"%@ (%@分)",model.Title,model.FullScore];
    NSString *passStr;
    if (model.IsPass) {
        passStr = @"通过";
    }else{
        passStr = @"未通过";
    }
    self.passName.text = [NSString stringWithFormat:@"%@分(%@）",model.Score,passStr];
    self.useTime.text = [NSString stringWithFormat:@"%ld",model.UseTime];
    self.avScore.text = model.AverageScore;
    self.topScore.text = model.MaxScore;
    if (model.IsAllowViewAnswer) {
        if (kIsEmptyString(model.OpenViewAnswerDate)) {
            self.lookBtn.hidden = NO;
            [self.lookBtn setTitle:@"查看解析" forState:UIControlStateNormal];
            self.lookBtn.userInteractionEnabled = YES;
        }else{
            self.lookBtn.hidden = NO;
            [self.lookBtn setTitle:[NSString stringWithFormat:@"%@后可查看答案及解析",model.OpenViewAnswerDate] forState:UIControlStateNormal];
            self.lookBtn.userInteractionEnabled = NO;
        }
    }else{
        self.lookBtn.hidden = YES;
    }
}
#pragma mark - CollectionView代理
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.dataArr.count;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    GMAnswerCards * cardModel = self.dataArr[section];
    return cardModel.Items.count;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *reusableView =nil;
    if (kind == UICollectionElementKindSectionHeader){
        GMExamHeadView * headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"GMExamHeadView" forIndexPath:indexPath];
        GMAnswerCards * cardModel = self.dataArr[indexPath.section];
        headView.name.text = cardModel.TypeName;
        reusableView = headView;
    }
    //如果底部视图
    if (kind ==UICollectionElementKindSectionFooter)
    {
        UICollectionReusableView *footerview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView"forIndexPath:indexPath];
        footerview.backgroundColor = [UIColor purpleColor];
        reusableView = footerview;
        
    }
    return reusableView;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    GMResultCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GMResultCell" forIndexPath:indexPath];
    GMAnswerCards *model = self.dataArr[indexPath.section];
    GMAnswerItem *itemModel = model.Items[indexPath.row];
    cell.itemModel = itemModel;
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(DEVICE_WIDTH, 44);
}
//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((DEVICE_WIDTH-60)/5, 50);
}

//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 10,10);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}


//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    GMAnswerCards *model = self.dataArr[indexPath.section];
    GMAnswerItem *itemModel = model.Items[indexPath.row];
    GMAnalysisVC *analysis = [[GMAnalysisVC alloc] init];
    analysis.baseModel = self.baseModel;
    analysis.index = [itemModel.SortNo integerValue];
    [self.navigationController pushViewController:analysis animated:YES];
    
}
/**返回*/
-(void)backItemClick{
    // 返回到指定
    for (UIViewController *temp in self.navigationController.viewControllers) {
        if ([temp isKindOfClass:[GMMyClassVC class]]) {
            [self.navigationController popToViewController:temp animated:YES];
             return;
        }else if ([temp isKindOfClass:[GMHomeVC class]]) {
            [self.navigationController popToViewController:temp animated:YES];
            return;
        }else{
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
    }
}

- (IBAction)lookBtnClick:(id)sender {
    GMAnalysisVC *analysis = [[GMAnalysisVC alloc] init];
    analysis.examId= self.examId;
    analysis.baseModel = self.baseModel;
    [self.navigationController pushViewController:analysis animated:YES];
}


@end
